import Request from 'luch-request'
import flyrise from './flyrise.js'
// import encode from './encode.js'
import {
	refreshToken
} from '../api/auth.js'

const http = new Request()
http.setConfig((config) => {
	/* 设置全局配置 */
	config.header = {
		...config.header
	}
	return config
})


http.interceptors.request.use((config) => {
	config.baseURL = flyrise.getBasePath() /* 根域名不同 */
	console.log('>>>token:::', flyrise.getToken());
	/* 请求之前拦截器。可以使用async await 做异步操作 */
	if (config.header.Authorization === undefined) {
		config.header = {
			...config.header,
			Authorization: flyrise.getToken()
		}
	}
	// #ifdef MP-WEIXIN
	let wechatId = flyrise.getWechatId()
	if (wechatId) {
		config.header = {
			...config.header
		}
	}
	// #endif
	return config
}, (config) => {
	return Promise.reject(config)
})


http.interceptors.response.use(async (response) => {
	/* 请求之后拦截器。可以使用async await 做异步操作  */
	console.log('>>>app-code-isReset-1：' + response.data.code);
	if (response.data.code == 401) { // token值过期
		let newToken = "";
		try {
			newToken = flyrise.isMicro() ? await sendNativeReseive() : await networkToken();
		} catch (e) {
			newToken = "";
		}
		if (!newToken) {
			reloginActivity()
			return
		}
		let config = await doRequestConfig(response, newToken)
		const resetResponse = await http.request(config)
		if (resetResponse) {
			response = resetResponse;
		}
	}
	return response
}, (response) => { // 请求错误做点什么。可以使用async await 做异步操作
	return Promise.reject(response)
})

/**小程序从原生 app 端获取 token 值*/
const sendNativeReseive = () => {
	return new Promise((resolve, reject) => {
		uni.sendNativeEvent('refresh_token', {
			msg: 'unimp refresh_token'
		}, ret => {
			if (ret != null && ret.isSuccess) {
				let token = ret.token
				uni.setStorageSync("token", token)
				resolve(token)
			} else {
				reject()
			}
		})
	})
}

/**网络获取 token 值*/
const networkToken = () => {
	return new Promise((resolve, reject) => {
		let refres = uni.getStorageSync("refresh_token", "")
		if (!refres) {
			reject()
			return
		}
		refreshToken(refres).then(res => {
			let data = res.data
			if (res.statusCode != 200 || !data || !data.access_token) {
				reject()
				return
			}
			let token = data.token_type + ' ' + data.access_token
			uni.setStorageSync("token", token)
			let refreshToken = data.refresh_token
			uni.setStorageSync("refresh_token", refreshToken)
			console.log("刷新成功")
			resolve(token)
		}).catch(err => {
			reject()
		})
	})
}

const reloginActivity = () => {
	if (flyrise.isMicro()) {
		uni.showModal({
			title: '温馨提示',
			content: `用户校验失败，请重新登录`,
			success: (res) => {
				if (res.confirm) {
					flyrise.finish()
				}
			}
		});
	} else {
		flyrise.logoutRelogin()
	}
}

const doRequestConfig = (res, token) => {
	return new Promise((resolve, reject) => {
		let config = res.config
		config.header.Authorization = token
		resolve(config)
	})
}

export {
	http
}